package com.hualian.coupon.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hualian.coupon.exception.BusinessException;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author Lxd
 * @Description TODO
 * @date 2020/10/22 6:08
 * @Version 1.0
 */
@RestControllerAdvice(basePackages = {"com.hualian.coupon.controller"})
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> aClass) {
        //如果接口返回的基本类型就是ResultV0 那就没有必要进行额外处理,返回false
        return !returnType.getParameterType().equals((ResultV0.class));
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        //String类型不能直接包装,所以要进行特别处理
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                return objectMapper.writeValueAsString(new ResultV0<>(data));
            } catch (JsonProcessingException e) {
                throw new BusinessException("返回String类型错误");
            }
        }

        return new ResultV0<>(data);
    }
}
